package com.zlkj.pro.modular.business.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.message.api.MessageApi;
import cn.stylefeng.roses.kernel.message.api.enums.MessageReadFlagEnum;
import cn.stylefeng.roses.kernel.message.api.pojo.request.MessageRequest;
import cn.stylefeng.roses.kernel.message.api.pojo.response.MessageResponse;
import cn.stylefeng.roses.kernel.message.db.entity.SysMessage;
import cn.stylefeng.roses.kernel.message.db.service.SysMessageService;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import cn.stylefeng.roses.kernel.system.modular.user.service.impl.SysUserServiceImpl;
import com.anji.captcha.util.StringUtils;
import com.zlkj.pro.core.enums.MsgTemplateEnum;
import com.zlkj.pro.core.exception.BusinessException;
import com.zlkj.pro.core.util.ConvertUtil;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.service.UsersService;
import com.zlkj.pro.modular.business.entity.AgentEntity;
import com.zlkj.pro.modular.business.entity.ReportEntity;
import com.zlkj.pro.modular.business.mapper.MessageMapper;
import com.zlkj.pro.modular.business.model.vo.MessageVO;
import com.zlkj.pro.modular.business.model.vo.ProductInfoVO;
import com.zlkj.pro.modular.business.service.AgentService;
import com.zlkj.pro.modular.business.service.MessageService;
import com.zlkj.pro.modular.business.service.ReportService;
import com.zlkj.pro.modular.wechat.enums.WeChatEnum;
import com.zlkj.pro.modular.wechat.event.TemplateBean;
import com.zlkj.pro.modular.wechat.event.TemplateEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.BUSINESS_EXCEPTION;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class MessageServiceImpl implements MessageService {

    @Autowired
    private SysMessageService sysMessageService;

    @Resource
    private MessageApi messageApi;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private UsersService usersService;

    @Resource
    private ApplicationContext publisher;
    @Autowired
    private ReportService reportService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private AgentService agentService;

    @Override
    public List<MessageVO> findList(Long userId, Integer readFlag, String queryString) {
        if (userId == null) {
            throw new BusinessException(BUSINESS_EXCEPTION, "userId不能为空");
        }
        MessageRequest request = new MessageRequest();
        request.setReceiveUserId(userId);
        if (readFlag != null) {
            request.setReadFlag(readFlag);
        }
        request.setSortBy("create_time,id desc");
        List<SysMessage> list = sysMessageService.findList(request);
        if (StringUtils.isNotEmpty(queryString)) {
            // 对消息标题和内容进行模糊搜索筛选 用filter处理
            list = list.stream().filter(sysMessage ->
                    sysMessage.getMessageTitle().contains(queryString)
                            || sysMessage.getMessageContent().contains(queryString)
            ).collect(Collectors.toList());
        }


        List<MessageVO> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            resultList = ConvertUtil.turn(list, MessageVO.class);

            resultList.forEach(messageVO -> {
                messageVO.setMessageContentWithOutLabel(removeHtmlTags(messageVO.getMessageContent()));
            });
        }
        return resultList;
    }

    public static String removeHtmlTags(String html) {
        // 使用正则表达式匹配HTML标签
        Pattern pattern = Pattern.compile("<[^>]*>");
        Matcher matcher = pattern.matcher(html);
        // 使用matcher.replaceAll("")替换匹配到的标签为空字符串，从而去除标签
        return matcher.replaceAll("");
    }

    @Override
    public MessageResponse detail(Long messageId) {
        MessageRequest messageRequest = new MessageRequest();
        messageRequest.setMessageId(messageId);
        return messageApi.messageDetail(messageRequest);
    }

    @Override
    public Integer countUnread(Long userId) {
        MessageRequest messageRequest = new MessageRequest();
        messageRequest.setReceiveUserId(userId);
        messageRequest.setReadFlag(0);//未读
        return messageApi.queryCount(messageRequest);
    }

    @Override
    public void sendMessage(MsgTemplateEnum template, Long reportId, List<Long> receiverUserIds, List<String> replaceStr, String desc) {
        ReportEntity report = reportService.getById(reportId);
        Long agentId = report.getAgentId();
        Long createUser = report.getCreateUser();

        if (CollectionUtils.isEmpty(receiverUserIds)) {
            receiverUserIds = new ArrayList<>();
        }

        // 所有的消息都给超管发一份
        receiverUserIds.add(1339550467939639299L);
        if (template.getItems().length != replaceStr.size()) {
            throw new BusinessException(BUSINESS_EXCEPTION, "模板替换内容数量和参数不一致!");
        }

        // 添加发送消息给BMSH管理员
        if (template.getSendBmshManager()) {
            List<Long> userIds = messageMapper.getSendBmshManagerId();
            receiverUserIds.addAll(userIds);
        }
        // 给报备单关联地域的BMSH员工发送消息
        if (template.getSendBmshYuanGong()) {
            List<Long> userIds = messageMapper.getSendBmshYuanGongId(agentId);
            receiverUserIds.addAll(userIds);
        }
        // 发送上级
        if (template.getSendLeader()) {
            Long leaderId = messageMapper.getSendBmshLeaderId(createUser);
            if (leaderId != null && leaderId != 0L) {
                receiverUserIds.add(leaderId);
            }
        }
        // 发送自己
        if (template.getSendSelf()) {
            receiverUserIds.add(createUser);
        }

        // 给小程序发送消息
        List<SysMessage> sendMsgList = new ArrayList<>();
        for (Long userId : receiverUserIds) {
            SysMessage sysMessage = new SysMessage();
            // 初始化默认值
            sysMessage.setMessageTitle(template.getTitle());
            sysMessage.setMessageContent(getMessageContent(template, replaceStr));
            sysMessage.setReadFlag(MessageReadFlagEnum.UNREAD.getCode());
            sysMessage.setSendUserId(1L);
            sysMessage.setMessageType(template.getMessageType());
            sysMessage.setReceiveUserId(userId);
            sysMessage.setMessageSendTime(new Date());
            sendMsgList.add(sysMessage);
        }
        sysMessageService.saveBatch(sendMsgList);

        // 同步发送微信公众号消息逻辑
        try {

            SysUser sysUser = sysUserService.getById(createUser);
            AgentEntity agent = agentService.getById(agentId);


            List<Long> userIds = sendMsgList.stream().map(SysMessage::getReceiveUserId).collect(Collectors.toList());
            List<User> userList = usersService.lambdaQuery().in(User::getUserId, userIds).list();

            //公众号openId为空代表未关注公众号，不发送公众号消息
            List<String> mpOpenIds = userList.stream().map(User::getWxMpOpenId).filter(StrUtil::isNotBlank).collect(Collectors.toList());


            // 获取当前日期和时间
            //LocalDateTime now = LocalDateTime.now();
            //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            //String formattedDateTime = now.format(formatter);
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 设置格式模式
            String formattedDateTime = dateFormatter.format(report.getCreateTime());

            // 报备延期申请通知-提交延期申请的时间
            if (template.getTitle().equals("报备延期申请通知")) {
                formattedDateTime = dateFormatter.format(report.getDelayApplyTime());
            }

            // 发送微信公众号消息
            publisher.publishEvent(new TemplateEvent(this, TemplateBean.builder()
                    .openIds(mpOpenIds)
                    .templateId(template.getWxTemplateId())
                    .type(WeChatEnum.WX_TEMPLATE_TYPE_2)
                    .value1(report.getCode())//订单编号
                    .value2(report.getCustomerName())//关联客户
                    .value3(sysUser.getRealName() + "(" + agent.getName() + ")")//业务员
                    .value4(desc)//审批状态
                    .value5(formattedDateTime)//订单时间
                    .build()));
        } catch (Exception e) {
            log.error("发送公众号消息失败", e);
        }


    }

    private String getMessageContent(MsgTemplateEnum template, List<String> replaceStr) {
        String[] items = template.getItems();
        StringBuilder content = new StringBuilder();
        // 遍历items 然后用对应的replace 组装消息内容
        for (int i = 0; i < items.length; i++) {
            content.append("<p>").append(items[i]).append("：").append(replaceStr.get(i)).append("</p>");
        }
        content.append("<p><span style=\"color: #e03e2d;\">").append("具体内容：").append(template.getContent()).append("</span></p>");
        return content.toString();
    }
}
